import axios from 'axios';
import storage from '@/libs/storage';
import appService from '@/service/app';

const UBT_DISTINCTID = 'UBT_DISTINCTID';
const UBT_ORIGINALID = 'UBT_ORIGINALID';
const UBT_PHONE = 'UBT_PHONE';
const UBT_ADDRESS = 'UBT_ADDRESS';
const UBT_IP = 'UBT_IP';
const UBT_POINT = 'UBT_POINT';

const IPURL = 'https://api.ipify.org';
const API = '/eagleeye/ubt';

class UBT {
  constructor(params) {
    this.domain = params.domain;
    this.version = params.version;
    this.deviceInfo = this.getDeviceInfo();

    this.ip = storage.get(UBT_IP);
    this.address = storage.get(UBT_ADDRESS);
    this.point = storage.get(UBT_POINT);

    // this.createOriginalId();
    // this.monitorIp();
    // this.geolocation();
  }

  eeLogUBT(action, event, properties) {
    const { deviceInfo, domain, version, address, point, ip } = this;
    const originalId = storage.get(UBT_ORIGINALID);
    const defaultProperties = {
      $manufacturer: deviceInfo.manufacturer,
      $model: deviceInfo.model,
      $os: deviceInfo.os,
      $os_version: deviceInfo.os_version,
      $app_version: version,
      $screen_width: window.screen.availWidth,
      $screen_height: window.screen.availHeight,
      $longitude: point ? point.lng : 0,
      $latitude: point ? point.lat : 0,
      $ip: ip,
      $province: address ? address.province : '',
      $city: address ? address.city : '',
      $district: address ? address.district : '',
      $market: appService.getChannel(),
      platform: 'H5',
      mobile: storage.get(UBT_PHONE)
    };
    const params = {
      domain,
      action,
      event,
      timestamp: (new Date()).getTime(),
      properties: Object.assign({}, defaultProperties, properties)
    };

    const userId = storage.get(UBT_DISTINCTID);
    /* if (userId) {
      params.distinctId = userId;
    } else {
      params.distinctId = originalId;
    } */
    if (userId) {
      params.properties.ubtUserid = userId;
    }
    params.distinctId = originalId;

    if (action === 'signin' || action === 'signup') {
      params.originalId = originalId;
    }

    const url = (action === 'signin' || action === 'signup') ? '/trackSignup' : '/trackEvent';

    axios({
      method: 'post',
      url: `${API}${url}`,
      data: params
    }).then((res) => {
      console.info('UBT Success');
    });
  }

  createOriginalId() {
    if (storage.get(UBT_ORIGINALID)) {
      return;
    }

    let d = new Date().getTime();
    const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
      const r = (d + (Math.random() * 16)) % 16 | 0;
      d = Math.floor(d / 16);
      return (c === 'x' ? r : ((r & 0x3) | 0x8)).toString(16);
    });

    storage.set(UBT_ORIGINALID, uuid);
  }

  monitorIp() {
    axios.get(IPURL).then((res) => {
      this.ip = res.data || '';

      storage.set(UBT_IP, this.ip);
    });

    setTimeout(() => {
      this.monitorIp();
    }, 60 * 1000);
  }

  geolocation() {
    try {
      const geo = new BMap.Geolocation();
      if (geo) {
        geo.getCurrentPosition((res) => {
          this.address = res.address;
          this.point = res.point;

          storage.set(UBT_ADDRESS, this.address);
          storage.set(UBT_POINT, this.point);
        });
      }
    } catch (error) {
      console.error(error);
    }

    setTimeout(() => {
      this.geolocation();
    }, 30 * 60 * 1000);
  }

  getDeviceInfo() {
    const models = 'phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone';
    const deviceInfo = { model: 'unknown', os: 'unknown', manufacturer: 'unknown', os_version: 'unknown' };

    let model = models.split('|');
    for (let i = 0; i < model.length; i++) {
      const item = model[i];
      if (navigator.userAgent.match(new RegExp(item))) {
        model = item;
        break;
      }
    }

    if (typeof model === 'string') {
      deviceInfo.model = model;
    }

    if (deviceInfo.model === 'Android') {
      deviceInfo.os = 'Android';
      let versionInfo = navigator.userAgent.toLowerCase().match(/android\s([0-9.]*)/);
      versionInfo = (versionInfo === null || versionInfo.length > 2)
        ? navigator.userAgent : versionInfo[1];
      deviceInfo.os_version = versionInfo;
    } else if ('iPhone|iPod|ios|iPad'.match(new RegExp(deviceInfo.model))) {
      deviceInfo.manufacturer = 'Apple';
      deviceInfo.os = 'iOS';
      let versionInfo = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
      versionInfo = (versionInfo !== undefined && versionInfo !== null) ? [
        parseInt(versionInfo[1], 10),
        parseInt(versionInfo[2], 10),
        parseInt(versionInfo[3] || 0, 10)
      ].join('.') : navigator.userAgent;
      deviceInfo.os_version = versionInfo;
    }

    return deviceInfo;
  }
}

export default UBT;
